<template>
  <div class="foreign-population-wrapper">
    <p class="title">
      综合条件查询
      <el-link class="advance-search-btn" type="primary" :underline="false" @click="toggleAdvance">
        高级搜索<i class="el-icon-caret-bottom el-icon--right"></i>
      </el-link>
    </p>
    <div class="form-search-area">
      <el-form :inline="true" :model="formInline" size="medium" class="demo-form-inline">
        <el-form-item label="中文姓名">
          <el-input v-model="formInline.chineseNameLike" placeholder="请输入中文姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="formInline.sex" placeholder="请选择性别" clearable>
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="formInline.cardNoLike" placeholder="请输入证件号码" clearable></el-input>
        </el-form-item>
        <el-form-item label="国籍（地区）">
          <el-select v-model="formInline.nationality" placeholder="请选择国籍" clearable>
            <el-option label="中国" value="中国"></el-option>
            <el-option label="日本" value="日本"></el-option>
            <el-option label="韩国" value="韩国"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="外文姓" v-show="advanceStatus">
          <el-input v-model="formInline.englishFamilyNameLike" placeholder="请输入外文姓" clearable></el-input>
        </el-form-item>
        <el-form-item label="外文名" v-show="advanceStatus">
          <el-input v-model="formInline.englishNameLike" placeholder="请输入外文名" clearable></el-input>
        </el-form-item>
        <el-form-item label="出生日期" v-show="advanceStatus">
          <el-date-picker
            v-model="formInline.birthDate"
            type="date"
            placeholder="请选择出生日期" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="来华目的" v-show="advanceStatus">
          <el-select v-model="formInline.purposeComingChina" placeholder="请选择来华目的" clearable>
            <el-option
              v-for="(item) in DICY.purposeComingChina"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职业名称" v-show="advanceStatus">
          <el-input v-model="formInline.professionLike" placeholder="请输入职业名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否重点关注人员" v-show="advanceStatus">
          <el-select v-model="formInline.focusPeople" placeholder="请选择是否重点关注人员" clearable>
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="medium" @click="searchOrg">查询</el-button>
          <el-button size="medium" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="right-btn-area">
        <el-button size="medium" type="primary" @click="popNewAddDialog">新增境外人口</el-button>
        <el-button size="medium">导入</el-button>
        <el-button size="medium">导出</el-button>
        <el-button size="medium" @click="batchDeletion">批量删除</el-button>
      </div>
    </div>
    <!-- 表格 开始-->
    <div class="table-area clearfix">
      <el-table :data="tableData" ref="multipleTable" @selection-change="selectionChange" v-loading="loading" stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" width="50">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="外文姓" prop="englishFamilyName"></el-table-column>
        <el-table-column label="外文名" prop="englishName"></el-table-column>
        <el-table-column label="中文姓名" prop="chineseName"></el-table-column>
        <el-table-column label="性别" prop="sex"></el-table-column>
        <el-table-column label="国籍（地区）" prop="nationality"></el-table-column>
        <el-table-column label="来华目的" prop="purposeComingChina">
          <template slot-scope="scope">{{convertKeyToVal(scope.row.purposeComingChina, DICY.purposeComingChina)}}</template>
        </el-table-column>
        <el-table-column label="联系方式" prop="contact"></el-table-column>
        <el-table-column label="操作" min-width="90">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" icon="el-icon-view" @click="viewDetail(scope.row.id)">查看</el-link>
            <el-link type="success" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.id)">编辑</el-link>
            <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="paging-self"
        background
        :current-page.sync="currentPage"
        @current-change="pageChange"
        layout="total, prev, pager, next"
        :total="totalCount">
      </el-pagination>
    </div>
    <!-- 表格 结束-->
    <!-- 对话框 开始 -->
    <el-dialog title="境外人口" :visible.sync="dialogFormVisible" width="840px" @closed="closeDialog">
      <el-form :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" ref="ruleDialog">
        <el-row>
          <el-col :span="12">
            <el-form-item label="外文姓" label-width="136px" prop="englishFamilyName">
              <el-input v-model="dialogForm.englishFamilyName" placeholder="请输入外文姓" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="外文名" label-width="136px" prop="englishName">
              <el-input v-model="dialogForm.englishName" placeholder="请输入外文名" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="中文姓名" label-width="136px" prop="chineseName">
              <el-input v-model="dialogForm.chineseName" placeholder="请输入中文姓名" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" label-width="136px" prop="sex">
              <el-select v-model="dialogForm.sex" placeholder="请选择性别" clearable>
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出生日期" label-width="136px" prop="birthDate">
              <el-date-picker
                v-model="dialogForm.birthDate"
                type="date"
                placeholder="请选择选择出生日期" clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国籍（地区）" label-width="136px" prop="nationality">
              <el-select v-model="dialogForm.nationality" placeholder="请选择国籍（地区）" clearable>
                <el-option label="中国" value="中国"></el-option>
                <el-option label="日本" value="日本"></el-option>
                <el-option label="韩国" value="韩国"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="宗教信仰" label-width="136px" prop="faith">
              <el-select v-model="dialogForm.faith" placeholder="请选择宗教信仰" clearable>
                <el-option
                 v-for="(item, index) in DICY.faith"
                 :key="index"
                 :label="item.name"
                 :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否重点关注人员" label-width="136px" prop="focusPeople">
              <el-select v-model="dialogForm.focusPeople" placeholder="请选择是否重点关注人员" clearable>
                <el-option label="是" value="Y"></el-option>
                <el-option label="否" value="N"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="证件代码" label-width="136px" prop="cardCode">
              <el-input v-model="dialogForm.cardCode" placeholder="请输入证件代码" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号码" label-width="136px" prop="cardNo">
              <el-input v-model="dialogForm.cardNo" placeholder="请输入证件号码" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="证件有效期" label-width="136px" prop="occurDate">
              <el-date-picker
                v-model="dialogForm.occurDate"
                type="daterange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" label-width="136px" prop="contact">
              <el-input v-model="dialogForm.contact" placeholder="请输入联系方式" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来华目的" label-width="136px" prop="purposeComingChina">
              <el-select v-model="dialogForm.purposeComingChina" placeholder="请选择来华目的" clearable>
                <el-option
                  v-for="(item) in DICY.purposeComingChina"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="职业类别" label-width="136px" prop="professionType">
              <el-input v-model="dialogForm.professionType" placeholder="请输入职业类别" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职业名称" label-width="136px" prop="profession">
              <el-input v-model="dialogForm.profession" placeholder="请输入职业名称" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务处所" label-width="136px" prop="serviceSpace">
              <el-input v-model="dialogForm.serviceSpace" placeholder="请输入服务处所" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现住地" label-width="136px" prop="currentResidence">
              <el-input v-model="dialogForm.currentResidence" placeholder="请输入现住地" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="现住门（楼）详址" label-width="136px" prop="currentAddress">
              <el-input v-model="dialogForm.currentAddress" type="textarea" placeholder="请输入现住门（楼）详址" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="抵达日期" label-width="136px" prop="arrivalDate">
              <el-date-picker
                v-model="dialogForm.arrivalDate"
                type="date"
                placeholder="请选择抵达日期" clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计离开日期" label-width="136px" prop="leaveDate">
              <el-date-picker
                v-model="dialogForm.leaveDate"
                type="date"
                placeholder="请选择预计离开日期" clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrg" v-if="dialogMode!==CNST.READ_MODE">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import {
  getPopulationForeignerList,
  addPopulationForeigner,
  getPopulationForeignerDetail,
  updatePopulationForeignerDetail,
  deletePopulationForeigner,
  deletePopulationForeignerBatch
} from '@/api/baseBusiness'
import { deepClone, convertDateToString } from '@/utils'
import { mapState } from 'vuex'
export default {
  name: 'ForeignPopulation',
  data () {
    return {
      advanceStatus: false,
      formInline: {
        chineseNameLike: '',
        sex: '',
        cardNoLike: '',
        nationality: '',
        englishFamilyNameLike: '',
        englishNameLike: '',
        birthDate: '',
        purposeComingChina: '',
        professionLike: '',
        focusPeople: ''
      },
      loading: false,
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      totalCount: 0,
      dialogFormVisible: false,
      dialogForm: {
        englishFamilyName: '',
        englishName: '',
        chineseName: '',
        sex: '',
        birthDate: '',
        nationality: '',
        faith: '',
        focusPeople: '',
        cardCode: '',
        cardNo: '',
        occurDate: '',
        contact: '',
        purposeComingChina: '',
        professionType: '',
        profession: '',
        serviceSpace: '',
        currentResidence: '',
        currentAddress: '',
        arrivalDate: '',
        leaveDate: ''
      },
      rules: {
        englishFamilyName: [{ required: true, message: '请输入 外文姓', trigger: 'blur' }],
        englishName: [{ required: true, message: '请输入 外文名', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择 性别', trigger: 'change' }],
        birthDate: [{ required: true, message: '请选择 出生日期', trigger: 'change' }],
        nationality: [{ required: true, message: '请选择 国籍（地区）', trigger: 'change' }],
        cardCode: [{ required: true, message: '请输入 证件代码', trigger: 'blur' }],
        cardNo: [{ required: true, message: '请输入 证件号码', trigger: 'blur' }],
        occurDate: [{ required: true, message: '请选择 证件有效期', trigger: 'change' }],
        contact: [{ required: true, message: '请输入 联系方式', trigger: 'blur' }],
        purposeComingChina: [{ required: true, message: '请选择 来华目的', trigger: 'change' }],
        currentResidence: [{ required: true, message: '请输入 现住地', trigger: 'blur' }],
        currentAddress: [{ required: true, message: '请输入 现住门（楼）详址', trigger: 'blur' }],
        arrivalDate: [{ required: true, message: '请输入 抵达日期', trigger: 'change' }],
        leaveDate: [{ required: true, message: '请输入 预计离开日期', trigger: 'change' }]
      },
      dialogMode: '', // 对话框的状态，新增，查看，编辑
      curId: '', // 点击查看或编辑的当前列表项的id
      options: this.DICY.jilian
    }
  },
  computed: {
    ...mapState([
      'areaId'
    ])
  },
  methods: {
    toggleAdvance () {
      // this.$refs.advancedForm.classList.toggle('shrink')
      this.advanceStatus = !this.advanceStatus
    },
    convertKeyToVal (code, arr) {
      arr = Array.isArray(arr) ? arr : []
      let resArr = arr.filter((item) => {
        return item.code === code
      })
      if (resArr.length === 0) {
        return ''
      }
      return resArr[0].name
    },
    searchOrg () {
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    resetSearch () {
      for (let key in this.formInline) {
        this.$set(this.formInline, key, '')
      }
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    batchDeletion () {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请勾选要删除的项!'
        })
      } else {
        var ids = this.multipleSelection.map((item) => {
          return item.id
        }).join(',')
        this.$confirm('确定删除, 是否继续?', '批量删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deletePopulationForeignerBatch({ ids }).then((res) => {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            })
            this.getOrgListAndShow()
          })
        })
      }
    },
    selectionChange (valArr) {
      this.multipleSelection = valArr
    },
    showToDialog (data) {
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.$set(this.dialogForm, key, data[key])
        }
      }
      if (data.cardValidDateBegin) {
        this.$set(this.dialogForm, 'occurDate', [])
        this.dialogForm.occurDate[0] = data.cardValidDateBegin
        this.dialogForm.occurDate[1] = data.cardValidDateEnd
      }
    },
    viewDetail (id) {
      this.dialogMode = this.CNST.READ_MODE
      this.dialogFormVisible = true
      getPopulationForeignerDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    editDetail (id) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = id
      getPopulationForeignerDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    deleteDetail (id) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deletePopulationForeigner({ id }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getOrgListAndShow()
        })
      })
    },
    pageChange (curPage) {
      this.currentPage = curPage
      this.getOrgListAndShow()
    },
    submitOrg () {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          // -----------------
          let requestData = deepClone(this.dialogForm)
          convertDateToString(requestData)
          if (requestData.occurDate) {
            requestData.cardValidDateBegin = requestData.occurDate[0]
            requestData.cardValidDateEnd = requestData.occurDate[1]
          }
          delete requestData.occurDate
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            requestData.areaId = this.areaId
            addPopulationForeigner(requestData).then((res) => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.id = this.curId
            updatePopulationForeignerDetail(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          }
          // -----------------
        } else {
          return false
        }
      })
    },
    async getOrgListAndShow () {
      try {
        this.loading = true
        let requestData = {
          page: this.currentPage,
          areaId: this.areaId,
          ...deepClone(this.formInline)
        }
        convertDateToString(requestData)
        var res = await getPopulationForeignerList(requestData)
        this.tableData = res.data.queryResult
        this.totalCount = res.data.totalCount
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    closeDialog () {
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.dialogForm[key] = ''
      }
    },
    handleChange (value) {
      console.log(value)
    }
  },
  mounted () {
    this.getOrgListAndShow()
  }
}
</script>

<style lang="scss" scoped>
.foreign-population-wrapper {
  background-color: #ffffff;
  margin-top: 12px;
  border-radius: 4px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  padding: 20px;
  .title {
    margin: 0;
    font-size: 15px;
    color: #333333;
    margin-bottom: 10px;
    .advance-search-btn {
      float: right;
      user-select: none;
    }
  }
  .form-search-area {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .right-btn-area {
      height: 58px;
    }
  }
  .table-area {
    .el-link {
      margin-right: 13px;
    }
    .el-pagination.paging-self {
      margin-top: 20px;
      float: right;
    }
  }
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-cascader,.el-select,.el-input-number {
        width: 100%;
      }
      .el-date-editor.el-input,.el-date-editor.el-input__inner {
        width: 100%;
      }
    }
  }
}
</style>
